<template>
  <div class="snow-page">
    <div id="map">
      <div class="map-control">
        <div class="temp">
          <div class="form">
            <a-input v-model="point" placeholder="请输入地址" style="width: 250px;margin:10px;margin-left: 30px;"></a-input>
            <a-button type="primary" @click="send" style="margin: 10px;color: black;">解析</a-button>
            <a-input v-model="point2" placeholder="请输入经纬度(如121.50109,31.23691),经纬度用逗号隔开"
              style="width: 250px;margin:10px"></a-input>
            <a-button type="primary" @click="send2" style="margin: 10px;color: black;">解析</a-button>
            <span style="margin-top: 20px;color: aliceblue;">污染源企业：</span>
            <a-select v-model="enterpriseId" placeholder="请选择" style="width: 300px;margin-top: 10px;" allow-search
              allow-clear>
              <a-option v-for="item in optionsList" :key="item.id" :label="item.name" :value="item.id">
              </a-option>
            </a-select>
            <a-button type="primary" style="margin:10px;color: black;" @click="handleSearch">搜索</a-button>
          </div>
        </div>
      </div>
    </div>

    <div
      style="position: absolute;right:30px;bottom: 10px;z-index: 9999999;width: 160px;height: 160px;background-color: aqua;">
      <img src="../../assets/img/homebg.png" alt="" srcset="" style="width: 100%;height: 100%;">
    </div>

    <a-modal v-model:visible="mapvisibleInfo" width="60%">
      <template #title>
        详情
      </template>
      <div>
        <PollutionSourceInfo />
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue"
import { getWrEnterpriseInfoAPI, getViolationsApi } from "@/api/modules/wrEnterpriseInfo/index";
import PollutionSourceInfo from './components/PollutionSourceInfo.vue';
import testImportJson from "../../utils/310151.json"
//--------------------变量-------------
const map = ref(null) as any

const point = ref("")
const optionsList = ref([]) as any

const enterpriseId = ref("")
const markers = ref([]) as any

const point2 = ref("")


const mapvisibleInfo = ref(false)

//------============方法============

onMounted(() => {
  initMap();
  initData();
})
//============定义方法=======
function initMap() {
  BM.Config.HTTP_URL = "http://127.0.0.1:9000";
  BM.accessToken = 'pk.eyJ1IjoiY3VzXzB1NWg4MDhzIiwiYSI6IjJsc3U0YjR0MndjeGU1Njl0NXBsY2VuaHAifQ.rlvo4fLnln1zsVpmwpPPBw';
  map.value = BM.map("map", "bigemap.dk296l8v", {
    center: [31.63830007340284, 121.67619327083231],
    zoom: 9,
    zoomControl: true,
    // rotateEnable: true,
    attributionControl: false
  });


  //两个图层叠加
  var layer1 = BM.tileLayer("bigemap.dk296l8v");
  var layer2 = BM.tileLayer("bigemap.7z2184ob");

  map.value.setMaxZoom(20);
  layer1.addTo(map.value);
  layer2.addTo(map.value);
  layer1.on("loading", () => {
    Object.assign(layer1.options, {
      maxZoom: 20,
    });
  });
  layer2.on("loading", () => {
    Object.assign(layer2.options, {
      maxZoom: 20,
    });
  });

  //添加鹰眼地图。指定地图ID号为前面相同的ID bigemap.zhongkexingtu；
  // var miniMap = new BM.Control.MiniMap('bigemap.c38vsig1', { toggleDisplay: true }).addTo(map.value);
  map.value.zoomIn();
  // 设置地图的旋转角度
  // map.value.setRotation(90); // 旋转地图45度

  // 初始添加模糊遮罩层
  addBlurOverlay();


  // map.value.fitBounds([
  //   [31.257471084594727, 121.11383819580078],
  //   [31.87462615966797, 122.242919921875]
  // ]);
}
const polygonArr = ref([]) as any;

const polygonArr1 = ref([]) as any;

const polygonArr2 = ref([]) as any;

const polygonArr3 = ref([]) as any;

const polygonArr4 = ref([]) as any;
const polygonArr5 = ref([]) as any;
const polygonArr6 = ref([]) as any;
function addBlurOverlay() {
  console.log(testImportJson)

  BM.geoJSON(testImportJson, {
    style: function () {
      return {};
    },
    onEachFeature: function (feature: any, layer: any) {
      var latlngs = layer.feature.geometry.coordinates;

      latlngs[0].forEach((v: any) => {
        getCooridnate(v);
      });
      latlngs[1].forEach((v: any) => {
        getCooridnate1(v);
      });

      latlngs[2].forEach((v: any) => {
        getCooridnate4(v);
      });

      latlngs[3].forEach((v: any) => {
        getCooridnate2(v);
      });

      latlngs[4].forEach((v: any) => {
        getCooridnate3(v);
      });

      latlngs[5].forEach((v: any) => {
        getCooridnate5(v);
      });
      latlngs[6].forEach((v: any) => {
        getCooridnate6(v);
      });

      polygonArr.value = [...new Set(polygonArr.value)];
      polygonArr1.value = [...new Set(polygonArr1.value)];
      polygonArr2.value = [...new Set(polygonArr2.value)];
      polygonArr3.value = [...new Set(polygonArr3.value)];
      polygonArr4.value = [...new Set(polygonArr4.value)];
      polygonArr5.value = [...new Set(polygonArr5.value)];
      polygonArr6.value = [...new Set(polygonArr6.value)];
      var latLngs = [
        [
          [-91, -181],
          [91, -181],
          [91, 181],
          [-90, 181],
        ], // 外环
        polygonArr.value, // 洞
        // polygonArr1.value,
        polygonArr2.value,
        // polygonArr5.value,
        polygonArr6.value
        // polygonArr3.value,
        // polygonArr4.value
      ];
      var polygon = BM.polygon(latLngs, {
        fillColor: "black",
        stroke: true,
        // weight: 300,
        fillOpacity: 0.6,
        color: "aqua",
        weight: 4,
        dashArray: [20, 10],
      }).addTo(map.value);
    },
  });
}


function addBlurOverlay1() {


  BM.geoJSON(testImportJson, {
    style: function () {
      return {};
    },
    onEachFeature: function (feature: any, layer: any) {
      var latlngs = layer.feature.geometry.coordinates;

      latlngs[1].forEach((v: any) => {
        getCooridnate1(v);
      });
      // console.log(window.polygonArr);
      polygonArr1.value = [...new Set(polygonArr1.value)];
      var latLngs = [
        [
          [-91, -181],
          [91, -181],
          [91, 181],
          [-90, 181],
        ], // 外环
        polygonArr1.value, // 洞
      ];
      var polygon = BM.polygon(latLngs, {
        fillColor: "black",
        stroke: true,
        // weight: 300,
        fillOpacity: 0.2,
        color: "aqua",
        weight: 6,
        dashArray: [20, 10],
      }).addTo(map.value);
    },
  });
}

function addBlurOverlay2() {


  BM.geoJSON(testImportJson, {
    style: function () {
      return {};
    },
    onEachFeature: function (feature: any, layer: any) {
      var latlngs = layer.feature.geometry.coordinates;

      latlngs[2].forEach((v: any) => {
        getCooridnate2(v);
      });
      // console.log(window.polygonArr);
      polygonArr2.value = [...new Set(polygonArr2.value)];
      var latLngs = [
        [
          [-91, -181],
          [91, -181],
          [91, 181],
          [-90, 181],
        ], // 外环
        polygonArr2.value, // 洞
      ];
      var polygon = BM.polygon(latLngs, {
        fillColor: "black",
        stroke: true,
        // weight: 300,
        fillOpacity: 0.1,
        color: "aqua",
        weight: 6,
        dashArray: [20, 10],
      }).addTo(map.value);
    },
  });
}


// 获取行政区域边界数据
function getCooridnate(arr: any) {
  // console.log(arr);
  arr.forEach((v: any, i: any) => {
    polygonArr.value.push([v[1], v[0]]);
  });
}
function getCooridnate1(arr: any) {
  // console.log(arr);
  arr.forEach((v: any, i: any) => {
    polygonArr1.value.push([v[1], v[0]]);
  });
}

function getCooridnate5(arr: any) {
  arr.forEach((v: any, i: any) => {
    polygonArr5.value.push([v[1], v[0]]);
  });
}

function getCooridnate6(arr: any) {
  arr.forEach((v: any, i: any) => {
    polygonArr6.value.push([v[1], v[0]]);
  });
}

function getCooridnate4(arr: any) {

  arr.forEach((v: any, i: any) => {
    polygonArr4.value.push([v[1], v[0]]);
  });
}

function getCooridnate2(arr: any) {
  // console.log(arr);
  arr.forEach((v: any, i: any) => {
    polygonArr2.value.push([v[1], v[0]]);
  });
}

function getCooridnate3(arr: any) {
  // console.log(arr);
  arr.forEach((v: any, i: any) => {
    polygonArr3.value.push([v[1], v[0]]);
  });
}


async function initData() {
  let res = await getWrEnterpriseInfoAPI() as any;
  if (res.success) {
    optionsList.value = res.data
  }
}

function clearAllMarkers() {
  markers.value.forEach((marker: any) => {
    map.value.removeLayer(marker);
  });
  markers.value = []; // 清空数组
}

function send() {

}

function send2() {

}
declare global {
  interface Window {
    toDetails: any; // or specify a more precise type instead of 'any'
  }
}

window.toDetails = function (info: any) {
  nvrPreview(info);
}

function nvrPreview(info: any) {
  mapvisibleInfo.value = true
}

async function handleSearch() {
  let obj = {
    enterpriseId: enterpriseId.value
  }
  const customIcon = BM.icon({
    iconUrl: "/icons/location.png",
    iconSize: [30, 30], // 图标大小
    iconAnchor: [12, 12], // 图标锚点（相对于图标左上角）
    // popupAnchor: [0, -32]
  });

  clearAllMarkers();
  let res = await getViolationsApi(obj) as any;
  for (let i = 0; i < res.data.length; i++) {
    const marker = BM.marker([res.data[i].latitude, res.data[i].longitude], {
      icon: customIcon
    }).addTo(map.value);
    markers.value.push(marker);


    res.data[i].adderss = res.data[i].adderss ? res[i].adderss : "暂无";
    res.data[i].complainantName = res.data[i].complainantName ? res.data[i].complainantName : "暂无";
    res.data[i].complainantPhone = res.data[i].complainantPhone ? res.data[i].complainantPhone : "暂无";
    res.data[i].penaltyTime = res.data[i].penaltyTime ? formatDate(res.data[i].penaltyTime) : "暂无"

    marker.bindPopup(createDetailedPopupContent(res.data[i]));
  }
}

function createDetailedPopupContent(data: any) {
  return "<div class='popup-content detail-view'>" +
    " <h3>" + data.name + "</h3>" +
    "<p>地址:" + data.adderss + "</p>" +
    "<p>投诉人:" + data.complainantName + "</p>" +
    "<p>投诉人电话:" + data.complainantPhone + "</p>" +
    "<p>处罚日期:" + (data.penaltyTime) + "</p>" +
    " <p><a href='javaScript:void(0)' style='cursor:pointer;' onclick='toDetails(" + JSON.stringify(data) + ")'>详情</a></p>" +
    " </div>"
}




function formatDate(val: any) {
  const date = new Date(val);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 加1并补零
  const day = String(date.getDate()).padStart(2, '0'); // 补零

  return `${year}-${month}-${day}`;
}
</script>

<style lang="scss" scoped>
.home-page {
  padding: $padding;
  background: $color-bg-1;
}

// ::v-deep .bigemap-pane {
//   transform: rotate(30deg) !important;
// }
#map {
  position: relative;
  width: 100%;
  height: 100vh;
  background-color: #00557f;



  //  transform: rotate(30deg);

  /* 等同于 rotateZ(45deg) */
  .map-control {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 1000;

    button {
      padding: 6px 12px;
      cursor: pointer;
      background: white;
      border: 1px solid #cccccc;

    }

  }
}
</style>
